/* eslint-disable no-underscore-dangle */
/* eslint-disable no-undef */
/* eslint-disable no-restricted-syntax */
// 构建一个视图，把字节数组写到缓存中，索引从0开始，大端字节序
export const getView = (bytes: any[]): DataView => {
  const view = new DataView(new ArrayBuffer(bytes.length));
  for (let i = 0; i < bytes.length; i += 1) {
    view.setUint8(i, bytes[i]);
  }
  return view;
};

// 字符串转ArrayBuffer
export const String2ArrayBuffer = (str: string, cb: (s: any) => void): void => {
  const b = new Blob([str]);
  const f = new FileReader();
  f.onload = (e): void => {
    if (e.target) cb(e.target.result);
  };
  f.readAsArrayBuffer(b);
};

// 合并类型化数组
export const concatenate = (ResultConstructor: any, ...arrays: any): any => {
  let totalLength = 0;
  for (const arr of arrays) {
    totalLength += arr.length;
  }

  const result = new ResultConstructor(totalLength);
  let offset = 0;
  for (const arr of arrays) {
    result.set(arr, offset);
    offset += arr.length;
  }
  return result;
};

// 字节流转字符串
export const byteToString = (arr: any[]): string => {
  if (typeof arr === 'string') {
    return arr;
  }
  let str = '';
  const _arr = arr;
  for (let i = 0; i < _arr.length; i += 1) {
    const one = _arr[i].toString(2);
    const v = one.match(/^1+?(?=0)/);
    if (v && one.length === 8) {
      const bytesLength = v[0].length;
      let store = _arr[i].toString(2).slice(7 - bytesLength);
      for (let st = 1; st < bytesLength; st += 1) {
        store += _arr[st + i].toString(2).slice(2);
      }
      str += String.fromCharCode(parseInt(store, 2));
      i += bytesLength - 1;
    } else {
      str += String.fromCharCode(_arr[i]);
    }
  }
  return str;
};

// 十进制转八位二进制
export const binary = (num: number, Bits: number): string => {
  const resArry = [];
  const xresArry = [];
  let i = 0;
  let currentNumber = num;
  // 除2取余
  for (; currentNumber > 0; ) {
    resArry.push(currentNumber % 2);
    currentNumber = Math.floor(currentNumber / 2);
    i += 1;
  }
  // 倒序排列
  for (let j = i - 1; j >= 0; j -= 1) {
    xresArry.push(resArry[j]);
  }
  // 报错
  if (Bits < xresArry.length) {
    console.log('控制位小于转换位数');
  }
  // 补0操作
  if (Bits) {
    for (let r = xresArry.length; r < Bits; r += 1) {
      xresArry.unshift('0');
    }
  }
  return xresArry.join().replace(/,/g, '');
};
